package com.yeskery.nut.view;

import com.yeskery.nut.core.MediaType;
import com.yeskery.nut.core.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * 基础Web渲染器
 * @author sprout
 * @version 1.0
 * 2022-07-02 21:58
 */
public abstract class BaseWebRender implements WebRender {

    /** 媒体类型 */
    protected final MediaType mediaType;

    /** 扩展属性 */
    protected Map<String, ?> extendAttributes;

    /**
     * 构建Web渲染器
     * @param mediaType 媒体类型
     */
    public BaseWebRender(MediaType mediaType) {
        this.mediaType = mediaType;
    }

    /**
     * 获取服务上下文路径
     * @return 服务上下文路径
     */
    public String getContextPath() {
        return "/";
    }

    /**
     * 获取基础属性map
     * @param request 请求对象
     * @return 基础属性map
     */
    protected Map<String, Object> getBaseStringKeyAttributes(Request request) {
        Map<String, Object> dataMap = new HashMap<>(64);
        dataMap.putAll(request.getAttributes());
        if (extendAttributes != null) {
            dataMap.putAll(extendAttributes);
        }
        dataMap.put("session", request.getSession());
        dataMap.put("request", request);
        dataMap.put("serverContext", request.getServerContext());
        dataMap.put("contextPath", getContextPath());
        return dataMap;
    }

    /**
     * 获取基础属性map
     * @param request 请求对象
     * @return 基础属性map
     */
    protected Map<Object, Object> getBaseObjectKeyAttributes(Request request) {
        Map<Object, Object> dataMap = new HashMap<>(64);
        dataMap.putAll(request.getAttributes());
        if (extendAttributes != null) {
            dataMap.putAll(extendAttributes);
        }
        dataMap.put("session", request.getSession());
        dataMap.put("request", request);
        dataMap.put("serverContext", request.getServerContext());
        dataMap.put("contextPath", getContextPath());
        return dataMap;
    }
}
